package com.idea.cery.springboot1.dao.impl;

import com.idea.cery.springboot1.bean.User;
import com.idea.cery.springboot1.dao.JdbcDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * @author cery
 */
@Repository
public class JdbcDaoImpl implements JdbcDao {

    @Autowired
    @Qualifier("db1JdbcTemplate")//声明jdbc使用的数据源
    private JdbcTemplate jdbcTemplate;


    @Override
    public int insert(User user) {
        String sql = "insert into user(id,name,age,sex) values(?,?,?,?)";
        int rs = 0;
        try {
            rs = jdbcTemplate.update(sql, new Object[]{user.getId(), user.getName(), user.getAge(), user.getSex()});
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return rs;
    }

    @Override
    public int deleteById(String id) {
        String sql = "delete from user where id=?";
        int rs = 0;
        try {
            rs = jdbcTemplate.update(sql, new Object[]{id});
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return rs;
    }

    @Override
    public int update(User user) {
        String sql = "update user set age=?, sex=? where id=" + user.getId();
        int rs = 0;
        try {
            rs = jdbcTemplate.update(sql, new Object[]{user.getAge(), user.getSex()});
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return rs;
    }

    @Override
    public List<Map<String, Object>> listAll() {
        List<Map<String, Object>> lm = jdbcTemplate.queryForList("select * from user");

        return lm;
    }
}
